/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p/>
 * Compile: JDK 1.6+
 * <p/>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p/>
 * 公司名称：江苏欧索软件有限公司
 * <p/>
 * 公司地址：中国苏州科技城青山路1号
 * <p/>
 * 网址: http://www.oceansoft.com.cn
 * <p/>
 * 作者: 090922(陈伟)
 * <p/>
 * 文件名: com.oceansoft.mobile.econsole.interceptor.ApiAccessInterceptor.java
 * <p/>
 * 类产生时间: 2014-6-4 0004 下午 12:42
 * <p/>
 * 负责人: 090922(陈伟)
 * <p/>
 * Email:javacspring@gmail.com
 * <p/>
 * 所在组 : 掌上公安应用平台
 * <p/>
 * 所在部门: 开发部--手持技术部
 * <p/>
 * <p/>
 */
package com.oceansoft.mobile.common.aop;

import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.dao.ICommonDao;
import com.oceansoft.mobile.oauth.service.ISecurityService;
import io.netty.util.internal.StringUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.lang.reflect.Method;

/**
 * 客户端API访问拦截器<br/>
 * 在此拦截器，需要处理请求客户端类型处理，访问频率、权限控制
 *
 * @author: chenw
 * @time: 2014-6-4 0004 下午 12:42
 */
public class ApiAccessInterceptor implements HandlerInterceptor {


    @Resource
    private ISecurityService securityService;
    @Resource
    private ICommonDao commonDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String merid = request.getParameter("merid");
        if (StringUtils.hasText(merid)) {
            request.getSession().setAttribute("merid", merid);
        }
        String url = request.getParameter("url");
        if (StringUtils.hasText(url)) {
            request.getSession().setAttribute("url", url);
        }

        String methodName = "";
        String className = "";   
        if (handler instanceof HandlerMethod) {
        	HandlerMethod hd =  (HandlerMethod) handler;
            Method a = hd.getMethod();
            className = hd.getMethod().getClass().getPackage().getName()+hd.getMethod().getClass().getName();
            methodName = a.getName();
            if ("gotoMicroPoliceIndex".equals(methodName) || "oauth2".equals(methodName) || "putAppUser".equals(methodName)||"getOpenId".equals(methodName)) {
                return true;
            }
        }

        //来源是苏州公安微信的校验openId , 其他的用授权服务器来校验
        String openId ="";
        if(merid.equals("1070")){
            return true;
        }else if(merid.equals("1069")){
             openId = (String) request.getSession().getAttribute("openIdjf");
        }else {
             openId = (String) request.getSession().getAttribute("openId");
        }

//            openId = "ol7bHt_is9uNAvUrfndvx4-vsI9k";
//            request.getSession().setAttribute("openId",openId);
//            System.out.println("ApiAccessInterceptor ----  session openId==="+openId);
            if (!StringUtils.hasText(openId)) {
            	String state = request.getRequestURL().toString();
                state = state.replace("http://wjw.szgaj.cn", "http://wjw.szgaj.cn");
            	
            	//判断是否为AJAX请求
                String header = request.getHeader("x-requested-with");
                if (null != header && header.equalsIgnoreCase("XMLHttpRequest")) {
                    response.setContentType("application/json;charset=UTF-8");
                    Writer writer = response.getWriter();
                    writer.write("{\"succ\":true,\"msg\":\"noOpenId\",\"statusCode\":\"200\"}");
                    writer.flush();
                    writer.close();
                } else {
                    
                    String u = "/oauth/oauth?state=" + state;
//                    String pamamsString = "";
//                    System.out.println("uuu=="+u);
//                    Map<String, String[]> paramMap = request.getParameterMap();
//                    Set<String>  paramMapKey = paramMap.keySet();
//                    for (String param : paramMapKey) {
//						if("".equals(pamamsString))
//						{
//							pamamsString += "?"+param+"="+paramMap.get(param)[0];
//						}
//						else
//						{
//							pamamsString += "&"+param+"="+paramMap.get(param)[0];
//						}
//					}
//                    if(!"".equals(pamamsString))
//                    {
//                    	u = u+pamamsString;
//                    }
//                    System.out.println("uuu=="+u);
                    request.getRequestDispatcher(u).forward(request, response);
                }
                return false;
            }
            else
            {
            	//session存在openID   如果是二维码扫码   判断一下当前用户是不是关注用户  必须采用数据库校验  否则要出现死循环
            }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
    
    private static String getClientIP(HttpServletRequest request) {
        String fromSource = "X-Real-IP";
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
            fromSource = "X-Forwarded-For";
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            fromSource = "Proxy-Client-IP";
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            fromSource = "WL-Proxy-Client-IP";
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            fromSource = "request.getRemoteAddr";
        }
        //client.info("App Client IP: "+ip+", fromSource: "+fromSource);
        return ip;
    }


    /***
     * 判断是否包含特殊字符（防止字符注入）
     * @param s
     * @return
     */
    private boolean checkCharFilter(String s){
        String sFiltered = filterDangerString(s);
        return (sFiltered.length()==s.length())?false:true;
    }

    private String filterDangerString(String value) {
        if (value == null) {
            return null;
        }
        value = value.replaceAll("\\|", "");
        value = value.replaceAll("&", "&");
        value = value.replaceAll(";", "");
        value = value.replaceAll("@", "");
        value = value.replaceAll("'", "");
        value = value.replaceAll("<", "<");
        value = value.replaceAll(">", ">");
        value = value.replaceAll("\\(", "");
        value = value.replaceAll("\\)", "");
        value = value.replaceAll("\\+", "");
        value = value.replaceAll("\r", "");
        value = value.replaceAll("\n", "");
        value = value.replaceAll("script", "");
        value = value.replaceAll("'", "");
        value = value.replaceAll(">", "");
        value = value.replaceAll("<", "");
        value = value.replaceAll("=", "");
        value = value.replaceAll("/", "");
        value = value.replaceAll("\"", "");
        value = value.replaceAll("\\.", "");
        value = value.replaceAll("%", "");
        value = value.replaceAll(":", "");
        value = value.replaceAll("http", "");
        value = value.replaceAll("iframe", "");
        return value;
    }

}
